import { motion } from 'framer-motion';
import { LoadingOutlined, SearchOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef } from 'react';
import { Template } from '../types';

interface TemplateSelectorProps {
  templates: Template[];
  selectedTemplate: Template | null;
  onSelectTemplate: (template: Template) => void;
}

export const TemplateSelector = ({
  templates,
  selectedTemplate,
  onSelectTemplate
}: TemplateSelectorProps) => {
  const [visibleTemplates, setVisibleTemplates] = useState(8);
  const [isLoading, setIsLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);

  // 处理滚动加载
  useEffect(() => {
    const handleScroll = () => {
      if (!containerRef.current || isLoading || !hasMore) return;

      const container = containerRef.current;
      const scrollBottom = container.scrollHeight - container.scrollTop - container.clientHeight;

      if (scrollBottom < 100) {
        loadMoreTemplates();
      }
    };

    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [isLoading, hasMore, templates.length]);

  // 加载更多模板
  const loadMoreTemplates = async () => {
    if (isLoading || !hasMore) return;

    setIsLoading(true);
    try {
      // 模拟加载延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const nextCount = Math.min(visibleTemplates + 8, templates.length);
      setVisibleTemplates(nextCount);
      setHasMore(nextCount < templates.length);
    } finally {
      setIsLoading(false);
    }
  };

  // 过滤模板
  const filteredTemplates = templates.filter(template =>
    template.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // 重置加载状态
  useEffect(() => {
    setVisibleTemplates(8);
    setHasMore(filteredTemplates.length > 8);
  }, [searchQuery, templates]);

  return (
    <div className="w-full h-full flex flex-col bg-white">
      {/* 标题栏 */}
      <div className="sticky top-0 z-10 px-6 py-4 border-b border-gray-100">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-medium text-gray-800">选择模板</h2>
          <div className="relative flex-1 max-w-md ml-4">
            <input
              type="text"
              placeholder="搜索模板..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 rounded-full bg-gray-50 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white transition-all"
            />
            <SearchOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
          </div>
        </div>
      </div>

      {/* 模板网格 */}
      <div ref={containerRef} className="flex-1 overflow-y-auto">
        <div className="grid grid-cols-2 gap-3 p-4">
          {filteredTemplates.slice(0, visibleTemplates).map((template) => (
            <motion.div
              key={template.id}
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              onClick={() => onSelectTemplate(template)}
              className={`relative aspect-[4/3] rounded-lg overflow-hidden cursor-pointer group ${
                selectedTemplate?.id === template.id 
                  ? 'ring-2 ring-blue-500 shadow-lg' 
                  : 'hover:shadow-md'
              }`}
            >
              {/* 模板图片 */}
              <img
                src={template.imageUrl}
                alt={template.name}
                className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                onError={(e) => {
                  e.currentTarget.src = './templates/default.png';
                }}
              />

              {/* 选中状态指示器 */}
              {selectedTemplate?.id === template.id && (
                <div className="absolute top-2 right-2 w-6 h-6 rounded-full bg-blue-500 flex items-center justify-center">
                  <div className="w-3 h-3 rounded-full bg-white"></div>
                </div>
              )}

              {/* 模板名称 - 简化显示 */}
              <div className="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/60 to-transparent">
                <p className="text-white text-sm font-medium truncate">{template.name}</p>
              </div>
            </motion.div>
          ))}
        </div>

        {/* 加载状态 */}
        {isLoading && (
          <div className="flex justify-center py-4">
            <div className="loading-spinner">
              <LoadingOutlined className="text-2xl text-blue-500" />
            </div>
          </div>
        )}

        {/* 加载完成提示 */}
        {!hasMore && filteredTemplates.length > 0 && (
          <div className="text-center py-4 text-gray-500 text-sm">
            已加载全部模板
          </div>
        )}

        {/* 无搜索结果提示 */}
        {filteredTemplates.length === 0 && (
          <div className="flex flex-col items-center justify-center py-8 text-gray-500">
            <SearchOutlined className="text-3xl mb-2" />
            <p>未找到匹配的模板</p>
          </div>
        )}
      </div>
    </div>
  );
}; 